<?php

namespace JLPay\Models;

/**
 * 基础响应类
 */
class BaseResponse
{
    protected array $originData;
    protected string $retCode;
    protected string $retMsg;

    /**
     * 构造函数
     *
     * @param array $data 响应数据
     */
    public function __construct(array $data)
    {
        $this->originData = $data;
        $this->retCode = $data['ret_code'] ?? '';
        $this->retMsg = $data['ret_msg'] ?? '';
        
        // 设置其他属性
        foreach ($data as $key => $value) {
            // 将下划线命名转换为驼峰命名
            $camelCaseKey = $this->snakeToCamel($key);
            if (property_exists($this, $camelCaseKey)) {
                $this->$camelCaseKey = $value;
            }
        }
    }

    /**
     * 判断响应是否成功
     *
     * @return bool
     */
    public function isSuccess(): bool
    {
        return $this->retCode === '00000' || $this->retCode === '00';
    }

    /**
     * 获取返回码
     *
     * @return string
     */
    public function getRetCode(): string
    {
        return $this->retCode;
    }

    /**
     * 获取返回消息
     *
     * @return string
     */
    public function getRetMsg(): string
    {
        return $this->retMsg;
    }

    /**
     * 获取原始数据
     *
     * @return array
     */
    public function getOriginData(): array
    {
        return $this->originData;
    }

    /**
     * 转换为数组
     *
     * @return array
     */
    public function toArray(): array
    {
        $data = [
            'ret_code' => $this->retCode,
            'ret_msg' => $this->retMsg
        ];
        
        // 添加所有公共属性
        $reflection = new \ReflectionClass($this);
        foreach ($reflection->getProperties(\ReflectionProperty::IS_PROTECTED) as $property) {
            $propertyName = $property->getName();
            if ($propertyName !== 'originData' && $propertyName !== 'retCode' && $propertyName !== 'retMsg') {
                $property->setAccessible(true);
                $value = $property->getValue($this);
                if ($value !== null) {
                    // 将驼峰命名转换为下划线命名
                    $snakeCaseName = $this->camelToSnake($propertyName);
                    $data[$snakeCaseName] = $value;
                }
            }
        }
        
        return $data;
    }

    /**
     * 驼峰命名转下划线命名
     *
     * @param string $camelCase
     * @return string
     */
    private function camelToSnake(string $camelCase): string
    {
        return strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $camelCase));
    }

    /**
     * 下划线命名转驼峰命名
     *
     * @param string $snakeCase
     * @return string
     */
    private function snakeToCamel(string $snakeCase): string
    {
        return lcfirst(str_replace('_', '', ucwords($snakeCase, '_')));
    }

    /**
     * 检查是否需要解密
     *
     * @return bool
     */
    public function requiresDecrypt(): bool
    {
        return true; // 默认所有成功响应都需要解密
    }
} 